
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
  user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: '1234',
    port: 5432,
});
class message {
    async messageGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.page || 0;
            const values = [limit, offset*limit]
            values.push(req.user.user.id)
            const queryText = `
            SELECT * FROM message where user_id=$3
            limit $1 offset $2
            `;
            console.log(queryText)
            const messages = result.rows;
            const nextOffset =  messages.length < limit ? 0 : parseInt(offset) + parseInt(limit);
            const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;
        
            const result = await pool.query(queryText, values);
            const response = {
              messages,
              next: nextOffset === 0 ? null : `http://localhost:${PORT}/messages?limit=${limit}&offset=${nextOffset}`,
              previous: previousOffset === null? null : `http://localhost:${PORT}/messages?limit=${limit}&offset=${previousOffset}`,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
        
    async messagePost (req, res){
        try {
          const {content, mode} = req.body
          const queryText = `
          INSERT INTO message (content, user_id, is_ai, mode)
          VALUES ($1, $2, $3, $4)
          RETURNING *;
          `;
          const values = [content, req.user.user.id, false, mode];
      
          const result = await pool.query(queryText, values);
          const message = result.rows[0];
          const response = {
            message
          };
      
          res.json(response);
        } catch (error) {
          res.status(500).json({ error: error.message });
        }
      }
}

module.exports = new message()